import axios from 'axios'
import store from 'store'
import { getToken,removeToken } from 'utils/auth'
import { Message } from 'element-ui';
import router from 'router'
import { Loading } from 'element-ui';
let loadingInstance;

// 创建axios实例
const service = axios.create({
  baseURL: "/", // api 的 base_url
  timeout: 15000, // 请求超时时间
  // headers: {
  //   'Content-Type': 'application/x-www-form-urlencoded'
  // }
})

// request拦截器
service.interceptors.request.use(
  config => {
     loadingInstance = Loading.service({
      lock: true,
      text: 'Loading',
      background: 'rgba(255,255,255,0.5)'
    });
    // if (store.getters.token) {
    //   config.headers['X-Token'] = getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
    // }
    return config
  },
  error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)

// response 拦截器
service.interceptors.response.use(
  response => {
    loadingInstance.close()
    
    
    const res = response.data
    // const headers = response.headers;
    /**
     * code为非1是抛错 可结合自己业务进行修改
     */
    if (res.code !== 1) {
      // if (res.code === 401) {
      //   console.log('token过期') // for debug
      // } else if (res.code === 4105) {
      //   removeToken()
      //   router.push({path:'/login'});
      // }
      Message.error(res.msg)
      return Promise.reject(res.msg)
    } else {
      return res
    }
  },
  error => {
    loadingInstance.close()
    return Promise.reject(error)
  }
)

export default service
